package www.wmx.com.xssc.util.threeUtil;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import www.wmx.com.xssc.domain.doc.kjjbj.*;
import www.wmx.com.xssc.domain.mb.RbtKjjlMbKjjbj;
import www.wmx.com.xssc.domain.vo.extract.BaseMatchResult;
import www.wmx.com.xssc.domain.vo.extract.request.LWRequest;
import www.wmx.com.xssc.domain.vo.extract.request.PatentRequest;
import www.wmx.com.xssc.domain.vo.extract.request.ZZRequest;
import www.wmx.com.xssc.domain.vo.response.KJJBJResponse;
import www.wmx.com.xssc.service.IRbtKjjlMbKjjbjService;
import www.wmx.com.xssc.service.kjjbj.*;
import www.wmx.com.xssc.util.ArticleProcessUtil;
import www.wmx.com.xssc.util.PatentProcessUtil;
import www.wmx.com.xssc.util.ZZProcessUtil;
import www.wmx.com.xssc.util.enumUtil.CgjlType;
import www.wmx.com.xssc.util.enumUtil.TjdjEnum;
import www.wmx.com.xssc.util.time.DateFormatterUtil;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 科技进步奖项的各个成果的罗列：
 */
@Data
@Slf4j
@Component
public class KjjbjProcessUtil {


    @Resource(description = "科技进步奖-软著-RbtKjjlKjjbjYdjjsjrjzzqzm")
    private IRbtKjjlKjjbjYdjjsjrjzzqzmService kjjlKjjbjYdjjsjrjzzqzmService;
    @Resource(description = "科技进步奖-论文-RbtKjjlKjjbjFblwjzzzm")
    private IRbtKjjlKjjbjFblwjzzzmService kjjlKjjbjFblwjzzzmService;
    @Resource(description = "科技进步奖-专利-RbtKjjlKjjbjFmzlzm")
    private IRbtKjjlKjjbjFmzlzmService kjjlKjjbjFmzlzmService;
    @Resource(description = "科技进步奖的基本信息")
    private IRbtKjjlKjjbjJbxxService kjjlKjjbjJbxxService;

    @Resource
    private ArticleProcessUtil articleProcessUtil;
    @Resource
    private PatentProcessUtil patentProcessUtil;
    @Resource
    private ZZProcessUtil zzProcessUtil;

    @Resource
    private IRbtKjjlKjjbjBjcgService kjjlKjjbjBjcgService;
    @Resource(description = "科技进步奖的勘探量模版的读取")
    private IRbtKjjlMbKjjbjService rbtKjjlMbKjjbjService;

    /**
     * 科技进步奖所有成果的处理过程：
     *
     * @param jbxxID
     */
    public KJJBJResponse processKjjbj(String jbxxID) {

        boolean flag = true;
        KJJBJResponse kjjbjResponse = new KJJBJResponse();
        List<LWRequest> lw = new ArrayList<>();
        List<PatentRequest> zl = new ArrayList<>();
        List<ZZRequest> zz = new ArrayList<>();

        //科技进步奖的基本信息：里面含有所有项目的相关信息：
        RbtKjjlKjjbjJbxx kjjbjJbxx = kjjlKjjbjJbxxService.lambdaQuery()
                .eq(RbtKjjlKjjbjJbxx::getId, jbxxID)
                .one();

        //成果登记：
        String cgdjFailReson = null;
        List<RbtKjjlKjjbjBjcg> jcyjjBjcgList = kjjlKjjbjBjcgService.lambdaQuery()
                .in(RbtKjjlKjjbjBjcg::getCgglDjId, kjjbjJbxx.getCgglDjId().split(",，"))
                .list();
        for (RbtKjjlKjjbjBjcg jcyjjBjcg : jcyjjBjcgList) {
            if (!(jcyjjBjcg != null && jcyjjBjcg.getKjjlKjjbjId() != null && jcyjjBjcg.getKjjlKjjbjId().equals(kjjbjJbxx.getId()))) {
                cgdjFailReson = "项目成果未完成成果登记";
                kjjbjResponse.setCgdjFailReson(cgdjFailReson);
                flag = false;
                break;
            }
        }

        //0. 专利数量、经济效益的比对、存储量、转化率
        List<String> failReasonsKjjbjMB = processKjjbjMB(kjjbjJbxx);
        if(failReasonsKjjbjMB!=null && !failReasonsKjjbjMB.isEmpty()){
            flag = false;
        }

        //1.论文：
        List<RbtKjjlKjjbjFblwjzzzm> jcyjjLwxxList = kjjlKjjbjFblwjzzzmService.lambdaQuery()
                .eq(RbtKjjlKjjbjFblwjzzzm::getKjjlKjjbjId, jbxxID)
                .list();
        if (jcyjjLwxxList != null && !jcyjjLwxxList.isEmpty()) {
            articleProcessUtil.init();
            for (RbtKjjlKjjbjFblwjzzzm lwxx : jcyjjLwxxList) {
                LWRequest lwRequest = initLwRequest(kjjbjJbxx, lwxx);
                BaseMatchResult result = articleProcessUtil.matchProcess(lwRequest);
                if (!result.isSuccess()) {
                    lwRequest.setFailReason(result.getFailReason());
                    lw.add(lwRequest);
                    flag = false;
                }
            }
        }
        //2.专利：
        List<RbtKjjlKjjbjFmzlzm> jcyjjFmzlzmList = kjjlKjjbjFmzlzmService.lambdaQuery()
                .eq(RbtKjjlKjjbjFmzlzm::getKjjlKjjbjId, jbxxID)
                .list();
        if (jcyjjFmzlzmList != null && !jcyjjFmzlzmList.isEmpty()) {
            patentProcessUtil.init();
            for (RbtKjjlKjjbjFmzlzm fmzlzm : jcyjjFmzlzmList) {
                PatentRequest patentRequest = initPatentRequest(kjjbjJbxx, fmzlzm);
                BaseMatchResult result = patentProcessUtil.matchProcess(patentRequest);
                if (!result.isSuccess()) {
                    patentRequest.setFailReason(result.getFailReason());
                    zl.add(patentRequest);
                    flag = false;
                }
            }
        }
        //3.专著：
        List<RbtKjjlKjjbjYdjjsjrjzzqzm> jcyjjZzxxList = kjjlKjjbjYdjjsjrjzzqzmService.lambdaQuery()
                .eq(RbtKjjlKjjbjYdjjsjrjzzqzm::getKjjlKjjbjId, jbxxID)
                .list();
        if (jcyjjZzxxList != null && !jcyjjZzxxList.isEmpty()) {
            zzProcessUtil.init();
            for (RbtKjjlKjjbjYdjjsjrjzzqzm zzxx : jcyjjZzxxList) {
                ZZRequest zzRequest = initZZRequest(kjjbjJbxx, zzxx);
                BaseMatchResult result = zzProcessUtil.matchProcess(zzRequest);
                if (!result.isSuccess()) {
                    zzRequest.setFailReason(result.getFailReason());
                    zz.add(zzRequest);
                    flag = false;
                }
            }
        }
        kjjbjResponse.setLwRequestList(lw);
        kjjbjResponse.setZlRequestList(zl);
        kjjbjResponse.setZzRequestList(zz);
        kjjbjResponse.setFailReason(failReasonsKjjbjMB);
        kjjbjResponse.setSuccess(flag);
        return kjjbjResponse;
    }


    private LWRequest initLwRequest(RbtKjjlKjjbjJbxx jcyjjJbxx, RbtKjjlKjjbjFblwjzzzm lwxx) {
        LocalDateTime start = DateFormatterUtil.StrToLocalDateTime(jcyjjJbxx.getXmzqq());
        LocalDateTime end = DateFormatterUtil.StrToLocalDateTime(jcyjjJbxx.getXmzqz());
        List<String> names = Arrays.stream(lwxx.getZz().split("、,，；;")).collect(Collectors.toList());
        LWRequest lwRequest = LWRequest.builder()
                .authorEnroll(names)
                .lwtm(lwxx.getLwzzmc())
                .qkmc(lwxx.getFbkwcbs())
                .fbny(LocalDate.from(DateFormatterUtil.StrToLocalDateTime(lwxx.getFbcbsj())))
//                .qtzz(lwxx.getQtzz()) 作者
//                .zzpm(0) 作者排名
//                .sciTycs(lwxx.getSciTycs()) 他引次数
//                .yxyz(lwxx.getYxyz()) 影响因子
                .build();
        lwRequest.setNd(jcyjjJbxx.getNd());
        lwRequest.setXmmc(jcyjjJbxx.getXmmc());
        lwRequest.setJbxxID(jcyjjJbxx.getId());
        lwRequest.setCgjlType(CgjlType.KJJBJ.getCode());
        lwRequest.setXmBeginTime(start);
        lwRequest.setXmEndTime(end);
        return lwRequest;
    }

    private PatentRequest initPatentRequest(RbtKjjlKjjbjJbxx jcyjjJbxx, RbtKjjlKjjbjFmzlzm fmzlzm) {
        LocalDateTime start = DateFormatterUtil.StrToLocalDateTime(jcyjjJbxx.getXmzqq());
        LocalDateTime end = DateFormatterUtil.StrToLocalDateTime(jcyjjJbxx.getXmzqz());
        PatentRequest patentRequest = PatentRequest
                .builder()
                .zlmc(fmzlzm.getZlmc())
                .fmr(fmzlzm.getFmr())
                .fmrList(Arrays.stream(fmzlzm.getFmr().split("、,，；;")).collect(Collectors.toList()))
                .zlh(fmzlzm.getSqh())
                .build();
        patentRequest.setNd(jcyjjJbxx.getNd());
        patentRequest.setXmmc(jcyjjJbxx.getXmmc());
        patentRequest.setJbxxID(jcyjjJbxx.getId());
        patentRequest.setCgjlType(CgjlType.KJJBJ.getCode());
        patentRequest.setXmBeginTime(start);
        patentRequest.setXmEndTime(end);
        return patentRequest;
    }

    private ZZRequest initZZRequest(RbtKjjlKjjbjJbxx jcyjjJbxx, RbtKjjlKjjbjYdjjsjrjzzqzm zzxx) {
        LocalDateTime start = DateFormatterUtil.StrToLocalDateTime(jcyjjJbxx.getXmzqq());
        LocalDateTime end = DateFormatterUtil.StrToLocalDateTime(jcyjjJbxx.getXmzqz());
        ZZRequest zzRequest = ZZRequest
                .builder()
                .zzmc(zzxx.getJsjrjzzqmc())
//                .sbsj(zzxx.getSbsj())
                .fbsj(LocalDate.from(zzxx.getWcrq()))
                .zz(zzxx.getZzqr())
                .authorEnroll(Arrays.stream(zzxx.getZzqr().split("、,，；;")).collect(Collectors.toList()))
                .build();
        zzRequest.setNd(jcyjjJbxx.getNd());
        zzRequest.setXmmc(jcyjjJbxx.getXmmc());
        zzRequest.setJbxxID(jcyjjJbxx.getId());
        zzRequest.setCgjlType(CgjlType.KJJBJ.getCode());
        zzRequest.setXmBeginTime(start);
        zzRequest.setXmEndTime(end);
        return zzRequest;
    }


    /**
     * @param kjjbjJbxx
     * @return
     */
    private List<String> processKjjbjMB(RbtKjjlKjjbjJbxx kjjbjJbxx) {
        List<String> failReasons = new ArrayList<>();
        String kjjbjJbxxTjdj = kjjbjJbxx.getTjdj();
        int tjdj = Integer.parseInt(kjjbjJbxxTjdj.substring(kjjbjJbxxTjdj.length()-2));
        String tjdjMessage = TjdjEnum.getByCode(tjdj).getMessage();
        RbtKjjlMbKjjbj rbtKjjlMbKjjbj = rbtKjjlMbKjjbjService.lambdaQuery()
                .eq(RbtKjjlMbKjjbj::getDj, String.valueOf(tjdj)).one();


        Integer zlsl = rbtKjjlMbKjjbj.getZlsl();//专利数量最低要求
        Float jjxy = rbtKjjlMbKjjbj.getJjxy();//经济效益最低要求(单位:万元)
        Float kccl = rbtKjjlMbKjjbj.getKccl();//开采储量最低要求(单位:亿立方米)
        Float csl = rbtKjjlMbKjjbj.getCsl();//采收率最低要求(无单位,后接%)

        String tgyyqk = kjjbjJbxx.getTgyyqk();
        String jlnjjxy = kjjbjJbxx.getJlnjjxy();
        String textProcessed = (tgyyqk + jlnjjxy).replaceAll(" ", "");

        Long kjjlKjjbjFmzlCount = kjjlKjjbjFmzlzmService.lambdaQuery().
                eq(RbtKjjlKjjbjFmzlzm::getKjjlKjjbjId, kjjbjJbxx.getId()).count();
        if (kjjlKjjbjFmzlCount < zlsl) {
            failReasons.add("项目未满足 [" + tjdjMessage + "] 专利数量 最低要求");
        }

        Pattern pattern = Pattern.compile("直接经济效益[\\u4e00-\\u9fa5]?(-)?(\\d+)?.?\\d*万元");
        Matcher matcher = pattern.matcher(textProcessed);
        if (matcher.find()) {
            String jjxyText = textProcessed.substring(matcher.start(), matcher.end());
            Matcher jjxyMatcher = Pattern.compile("(-)?(\\d+)?.?\\d*万元").matcher(jjxyText);
            if (jjxyMatcher.find()) {
                float jjxyMatched = Float.valueOf(jjxyText.substring(jjxyMatcher.start(), jjxyMatcher.end() - 2));
                if (jjxyMatched < jjxy) {
                    failReasons.add("项目未满足 [" + tjdjMessage + "] 新增直接经济效益最低要求");
                }
            }
        }
//        else {
//            failReasons.add("未找到 新增直接经济效益 相关描述");
//        }


        pattern = Pattern.compile("探明可采储量[\\u4e00-\\u9fa5]?(-)?(\\d+)?.?\\d*亿");
        matcher = pattern.matcher(textProcessed);
        if (matcher.find()) {
            String kcclText = textProcessed.substring(matcher.start(), matcher.end());
            Matcher kcclMatcher = Pattern.compile("(-)?(\\d+)?.?\\d*亿").matcher(kcclText);
            if (kcclMatcher.find()) {
                float kcclMatched = Float.valueOf(kcclText.substring(kcclMatcher.start(), kcclMatcher.end() - 1));
                if (kcclMatched < kccl) {
                    failReasons.add("项目未满足 [" + tjdjMessage + "] 新增探明可采储量 最低要求");
                }
            }
        }
//        else {
//            failReasons.add("未找到 新增探明可采储量 相关描述");
//        }

        pattern = Pattern.compile("采收率[\\u4e00-\\u9fa5]?(-)?(\\d+)?.?\\d*%");
        matcher = pattern.matcher(textProcessed);
        if (matcher.find()) {
            String cslText = textProcessed.substring(matcher.start(), matcher.end());
            Matcher jjxyMatcher = Pattern.compile("(-)?(\\d+)?.?\\d*%").matcher(cslText);
            if (jjxyMatcher.find()) {
                float cslMatched = Float.valueOf(cslText.substring(jjxyMatcher.start(), jjxyMatcher.end() - 1));
                if (cslMatched < csl) {
                    failReasons.add("项目未满足 [" + tjdjMessage + "] 提高采收率 最低要求");
                }
            }
        }
//        else {
//            failReasons.add("未找到 提高采收率 相关描述");
//        }


        return failReasons;
    }

}
